library(plyr)
library(stringr)
library(devtools)
library(doParallel)
library(foreach)


#install_github("parallelExe","laurieKell")
#install_github("r4mfcl_git","hoyles",subdir="R4MFCL.src/R4MFCL")

library(parallelExe)
library(R4MFCL)
  
dirInp="http://scrs2014.googlecode.com/svn/trunk/alb-mse/Inputs"
dirInp="/home/laurie/Desktop/scrs2014/alb-mse/Inputs"

flts=t(array(c(
   "1","Spain","BB",   	      #ESP_BB	1981-2011/	FRA_BB	1981-2011/	MWTD	all	flags	1981-2011																																																							
	 "2","SpainFrance","TR",	  #ES+FR_TR	1930-49/	ESP_TR	1950-2011/	FRA_TR	1950-2011/	EU(ES,FR,UK,IR)_GN	1989-2011																																																							
	 "3","SpainFrance","BB",	  #ES.Cantabric_BB	1948-80/	FRA_BB	1948-80																																																											
	 "4","Portugal","BB",	      #PRT_BB	1958-2011/	ES(Canary,	Cadiz,	Azores)_BB	1958-2011																																																									
	 "5","Japan","LL",	        #JPN	LL	ALB	target	period	1956-1969																																																									
	 "6","Japan","LL",	        #JPN	LL	ALB	transition	period	1970-1975																																																									
	 "7","Japan","LL",	        #JPN	LL	ALB	bycatch	period	1976-2011																																																									
	 "8","China-Taipei","LL",	  #TAI_LL	1950-1986/	all	other	LL	fleets	1950-1986(excluding	Fishery	9																																																						
	 "9","China-Taipei","LL",	  #TAI_LL	1987-1998/	all	other	LL	1987-1998	(excluding	Fishery	9																																																						
	"10","China-Taipei","LL",	  #TAI_LL	1999-2011/	all	other	LL	1999-2011	(excluding	Fishery	9																																																						
	"11","Korea","LL",	        #KR+PA_LL	1964-2011/	KOR_LL	1964-2011/	PAN_LL	1964-07/	CUB_LL	1964-93																																																							
	"12","Others","SU"),        #CPV_BB/	VEN_BB/	others_BB/	others(IRL,PRT,GND,VCT,LCA,etc)_TR/	other	SURF	gears	1972-2011																																																							
c(3,12)))
flts=data.frame(Flag=as.factor(flts[,2]),Gear=as.factor(flts[,3]))

scen=list(OM=expand.grid(## all files
                         data   =c("BC","Tag"),
                         ## ini file
                         Biology=factor(c("BC", "Life History", "Santiago")),
                         ## frq file
                         cpue   =1:2,
                         cas    =factor(c("Include C-T","Exclude C-T","Exclude All")),
                         ## doitall
                         sel    =1:2,
                         rdv    =c(10,20),
                         ssz    =1:2))
scen=scen[[1]]
files  =c("doitall.albn","albn.frq","albn.ini")

## This sets up the different scenarios prior to running them
set=function(i,scen,files,dirInp="/home/laurie/Desktop/scrs2014/alb-mse/Inputs",dir="/home/laurie/temp"){

  dir=paste(dir,i,sep="")
  
  attach(scen[1,])

  ## Create input files and put in temp dir
  fileTmp=paste(dir,files,sep="/")
  
  if (file.exists(dir))
     try(system(paste("rm -R",dir), intern = TRUE, ignore.stderr = TRUE))
  
  dir.create(dir)
  #file.copy("/home/laurie/Desktop/scrs2014/alb-mse/Inputs/BC/albn.frq",fileTmp[2])
  #file.copy("/home/laurie/Desktop/scrs2014/alb-mse/Inputs/BC/albn.ini",fileTmp[3])
  #file.copy("/home/laurie/Desktop/scrs2014/alb-mse/Inputs/BC/doitall.albn",fileTmp[1])
  
  write.frq(fileTmp[2],read.frq(paste(dirInp,data,files,sep="/")[2]))
  write.ini(fileTmp[3],read.ini(paste(dirInp,data,files,sep="/")[3]))
  cat(scan(paste(dirInp,data,files,sep="/")[1],what="",sep="\n",skip=1),file=fileTmp[1],sep="\n")

  ### Modify input files 
  ##  ini file
  #   Biology 
  ini=mlply(c("BC/albn.ini","Tag/albn.ini","LifeHistory.ini","Santiago.ini"),
               function(x,dir) read.ini(paste(dirInp,x,sep="/")), dir=dirInp)
  names(ini)=c("BC","Tag","LifeHistory","Santiago")
    
  if (Biology%in%c("BC","Tag")){
    ini[[data]]$mat     =ini[[Biology]]$mat
    ini[[data]]$M       =ini[[Biology]]$M
    ini[[data]]$age_pars=ini[[Biology]]$age_pars}

  write.ini(fileTmp[3],ini[[data]])

  ## frq file
  frq=read.frq(fileTmp[2])

  # cpue
  frq$mat[frq$mat[,"fishery"]==1,"effort"]=-1
  # cas
  frq$mat[frq$mat[,"fishery"]==1,7]=-1
  
  write.frq(fileTmp[2],frq)

  ## doitall
  if (data=="BC")
    doit=readDoitall(paste(dirInp,"/doitall.base",sep="")) else
    doit=readDoitall(paste(dirInp,"/doitall.tag",sep=""))

  doit$sel
  doit$selgrp
  doit$cpue
  doit$sample
  doit$rdev
  
  writeDoitall(fileTmp[1],doit)
  }
  
## This runs the different scenarios
run=function(dir,files){
  
  ## Get input files
  fileTmp=paste(dir,files,sep="/")
  
  doitallFn("mfclo64",fileTmp,dir=dir)
  }

## function to do something at the end
get=function(files,to){
  
  mfcl         =readMFCL(files)
  catch.n(mfcl)=landings.n(mfcl)+discards.n(mfcl)
  
  save(mfcl,file=to)}

## run 1 by 1
# Start the clock!
tm1=proc.time()
oneByone=run(1,scen,files,dir="/home/laurie/temp")
# Stop the clock
tm1=proc.time()-tm1
                   
## run in parallel
cl=makeCluster(4)
registerDoParallel(cl)

tm2=proc.time()
  res=foreach(j=1:4, 
            .multicombine=TRUE,
            .packages    =c("R4MFCL","parallelExe","plyr","stringr")) %dopar% { 
              
            run(i=j,scen,files,dir="/home/laurie/temp")
            }
tm2=proc.time()-tm2
